package com.code.coinprice.managers;

import com.code.coinprice.consts.CommonConstant;
import com.code.coinprice.models.CoinPriceSource;
import com.code.coinprice.models.RelativeCoinPrice;
import com.code.coinprice.services.CoinPriceDictService;
import com.code.coinprice.services.CoinPriceService;
import com.code.coinprice.services.CoinPriceSourceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

@Component
public class CoinPriceManager implements InitializingBean, ApplicationContextAware {

    private static final Logger log = LoggerFactory.getLogger(CoinPriceManager.class);

    private ApplicationContext applicationContext;

    private Map<String, Supplier<List<RelativeCoinPrice>>> coinPriceMap = new HashMap<>();

    public static Map<String, String> heartBeatMap = new HashMap<>();

    @Resource
    private CoinPriceSourceService coinPriceSourceService;

    @Resource
    private CoinPriceDictService coinPriceDictService;

    @Override
    public void afterPropertiesSet() {
        String heartCheckOff = coinPriceDictService.getDictValueByDictKey(CommonConstant.HEART_CHECK_OFF);
        heartBeatMap.put(CommonConstant.HEART_CHECK_OFF, heartCheckOff);
        List<CoinPriceSource> coinPriceSourceList = coinPriceSourceService.getCoinPriceSourceList();
        if (!CollectionUtils.isEmpty(coinPriceSourceList)) {
            for (CoinPriceSource coinPriceSource : coinPriceSourceList) {
                coinPriceMap.put(coinPriceSource.getSource(), () -> applicationContext.getBean(coinPriceSource.getSource().toLowerCase() + CommonConstant.BEAN_NAME_SUFFIX, CoinPriceService.class).getCoinPriceList(coinPriceSource));
            }
        }

    }

    public List<RelativeCoinPrice> getCoinPriceListBySource(String source) {
        Supplier<List<RelativeCoinPrice>> coinPriceSupplier = coinPriceMap.get(source);
        if (coinPriceSupplier != null) {
            return coinPriceSupplier.get();
        }
        return Collections.emptyList();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
